import logging
import time

import rel
import websocket

from model.WebsocketClientVO import WebsocketClientVO
from service.ClashService import ClashService
from service.CommandDispatcherService import CommandDispatcherService


class WebsocketClientService:
    def __init__(self, clientVo: WebsocketClientVO):
        self.ws = None
        self.clientVo = clientVo
        self.clashService = ClashService(self.clientVo)
        self.dispatcher = CommandDispatcherService(clientVo)


    def registerClientData(self):
        return "{}/{}".format(self.clientVo.clientInfo,
                              # self.clashService.getCurrentProxyFormClash()
                              '-1'
                              )

    def onMessage(self, ws, message):
        try:
            self.dispatcher.dispatch(ws, message)
        except Exception as e:
            logging.exception(e)

    def onError(self, ws, error):
        print(f"发生错误: {error}")

    def onClose(self, ws, closeStatusCode, closeMsg):
        print("连接已关闭")
        self.start()

    def onOpen(self, ws):
        pass


    def start(self):
        while True:
            try:
                target = self.clientVo.host + self.registerClientData()
                self.ws = websocket.WebSocketApp(target,
                                                 on_open=self.onOpen,
                                                 on_message=self.onMessage,
                                                 on_error=self.onError,
                                                 on_close=self.onClose
                                                 )
                self.clientVo.serverWs = self.ws
                self.ws.run_forever(dispatcher=rel, reconnect=5)
                break
            except Exception as e:
                logging.exception(e)
                time.sleep(30)